import vue from 'vue'
import Vuex from 'vuex'
import router,{resetRouter} from "../router";
import createPersistedState from 'vuex-persistedstate'
vue.use(Vuex)
// Vuex的设计（设置共享状态）jwttoken
function addNewRoute(menuList) {
    console.log(menuList)
    let routes = router.options.routes
    console.log(routes)
    routes.forEach(routeItem=>{
        if(routeItem.path=="/Index"){
            menuList.forEach(menu=>{
                if(menu.children && menu.children.length > 0){
                    menu.children.forEach(menuChildren=>{
                        let childRoute =  {
                            path:menuChildren.url,
                            name:menuChildren.urlname,
                            meta:{
                                title:menuChildren.name
                            },
                            component:()=>import('../components'+menuChildren.component)
                        }
                        routeItem.children.push(childRoute)
                    })
                }
            })
        }
    })
    resetRouter()
    router.addRoutes(routes)
}


export default new Vuex.Store({
    state: {
        menu: [],
        token:''
    },
    mutations: {
        setMenu(state,menuList) {
            state.menu = menuList
            addNewRoute(menuList)
        },
        setRoute(state,menuList) {
            addNewRoute(menuList)
        },
        setToken(state, token){
            state.token = token;
            sessionStorage.setItem("token",token);  //存储token
        },
        resetState(state){
            state.token = '';
            sessionStorage.clear();        //清除token
        }
    },
    getters: {
        getMenu(state) {
            return state.menu
        }
    },
    plugins:[createPersistedState()]
})